package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.SeckillVoucher;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisWorker;
import com.hmdp.utils.SimpleRedisLock;
import com.hmdp.utils.UserHolder;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.aop.framework.AopContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.connection.stream.*;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {

    @Resource
    private ISeckillVoucherService seckillVoucherService;

    @Resource
    private RedisWorker redisWorker;

    @Resource
    StringRedisTemplate stringRedisTemplate;

    @Resource
    RedissonClient redissonClient;

    //生成脚本
    private static final DefaultRedisScript<Long> SECKILL_SCRIPT;
    static{
        SECKILL_SCRIPT = new DefaultRedisScript<>();
        SECKILL_SCRIPT.setLocation(new ClassPathResource("seckillorder.lua"));
        SECKILL_SCRIPT.setResultType(Long.class);
    }
    //一步处理线程池
    private static final ExecutorService SECKILL_ORDER_EXECUTOR = Executors.newSingleThreadExecutor();


    @PostConstruct
    private void init(){
        SECKILL_ORDER_EXECUTOR.submit(new VoucherHandler());
    }

    private class VoucherHandler implements Runnable {
        private final String queueName = "stream.orders";
        @Override
        public void run() {
            while(true){
                //获取订单
                try {
                   //1获取消息队列中的消息 xreadgroup group g1 c1 count 1 block 2000 streams stream.orders >
                    List<MapRecord<String, Object, Object>> list = stringRedisTemplate.opsForStream().read(
                            Consumer.from("g1", "c1"),
                            StreamReadOptions.empty().count(1).block(Duration.ofSeconds(2)),
                            StreamOffset.create(queueName, ReadOffset.lastConsumed())
                    );
                    //2 判断是否获取成功
                    if(list == null || list.isEmpty()){
                        //2.1 失败返回
                        continue;
                    }

                    //3 成功 解析消息
                    MapRecord<String, Object, Object> entries = list.get(0);
                    Map<Object, Object> values = entries.getValue();
                    VoucherOrder  voucherOrder = BeanUtil.fillBeanWithMap(values, new VoucherOrder(), true);
                    //4 创建订单
                    handleVoucherOrder(voucherOrder);
                    //5 ack确认
                    stringRedisTemplate.opsForStream().acknowledge(queueName, "g1", entries.getId());
                } catch (Exception e) {
                    log.error("创建订单异常");
                    handlePandingList();
                }

            }
        }

        private void handlePandingList() {
            while(true){
                //获取订单
                try {
                    //1获取panding-list中的消息 xreadgroup group g1 c1 count 1 block 2000 streams stream.orders >
                    List<MapRecord<String, Object, Object>> list = stringRedisTemplate.opsForStream().read(
                            Consumer.from("g1", "c1"),
                            StreamReadOptions.empty().count(1),
                            StreamOffset.create(queueName, ReadOffset.from("0")));

                    //2 判断是否获取成功
                    if(list == null || list.isEmpty()){
                        //2.1 失败  没有消息
                        break;
                    }

                    //3 成功 解析消息
                    MapRecord<String, Object, Object> entries = list.get(0);
                    Map<Object, Object> values = entries.getValue();
                    VoucherOrder  voucherOrder = BeanUtil.fillBeanWithMap(values, new VoucherOrder(), true);
                    //4 创建订单
                    handleVoucherOrder(voucherOrder);
                    //5 ack确认
                    stringRedisTemplate.opsForStream().acknowledge(queueName, "g1", entries.getId());
                } catch (Exception e) {
                    log.error("pingding-list异常");

                }

            }
        }

//    private BlockingQueue<VoucherOrder> orderTasks = new ArrayBlockingQueue<>(1024 * 1024);
//    private class VoucherHandler implements Runnable {
//
//        @Override
//        public void run() {
//            while(true){
//                //获取订单
//                try {
//                    VoucherOrder voucherOrder = orderTasks.take();
//                    //创建订单
//                    handleVoucherOrder(voucherOrder);
//                } catch (InterruptedException e) {
//                    log.error("创建订单异常");
//                }
//
//            }
//        }

        private void handleVoucherOrder(VoucherOrder voucherOrder) {
            Long userId = voucherOrder.getUserId();
            // 1 获取锁对象
            RLock lock = redissonClient.getLock("lock:order:" + userId);
            boolean isLock = lock.tryLock();
            //2 失败
            if(!isLock){
                log.error("无法重复下单！");
            }
            //3 成功执行业务
            try{

                proxy.createVoucherOrder(voucherOrder);
            }finally {
                lock.unlock();
            }
        }
    }
    IVoucherOrderService proxy;
    @Override
    public Result seckillVoucher(Long voucherId){

        //1 查询优惠卷
        SeckillVoucher voucher = seckillVoucherService.getById(voucherId);
        //2 判断秒杀开始时间
        if(voucher.getBeginTime().isAfter(LocalDateTime.now())){
            return Result.fail("秒杀尚未开始！");
        }
        //3 判断秒杀结束时间
        if(voucher.getEndTime().isBefore(LocalDateTime.now())){
            return Result.fail("秒杀已经结束！");
        }

        Long userId = UserHolder.getUser().getId();
        //生成订单id
        Long orderId = redisWorker.nextId("order");
        //4 执行lua脚本
        Long result = stringRedisTemplate.execute(SECKILL_SCRIPT,
                Collections.emptyList(),
                voucherId.toString(), userId.toString(), orderId.toString());
        int r = result.intValue();
        //判断非零
        if(r != 0){
            return r == 1 ? Result.fail("库存不足！") : Result.fail("用户已下过单!");
        }

        //5 将订单存入消息队列
        //创建订单
        VoucherOrder voucherOrder = new VoucherOrder();
        //生成主键id
        Long id = redisWorker.nextId("order");
        voucherOrder.setId(id);
        // 下单用户id
        voucherOrder.setUserId(UserHolder.getUser().getId());
        // 代金券id
        voucherOrder.setVoucherId(voucherId);
        //放入阻塞队列

        //创建代理对象
        proxy = (IVoucherOrderService) AopContext.currentProxy();
        //6 返回订单id
        return Result.ok(orderId);

    }

//    @Override
//    @Transactional
//    public Result seckillVoucher(Long voucherId) {
//        //1 查询优惠卷
//        SeckillVoucher voucher = seckillVoucherService.getById(voucherId);
//        //2 判断秒杀开始时间
//        if(voucher.getBeginTime().isAfter(LocalDateTime.now())){
//            return Result.fail("秒杀尚未开始！");
//        }
//        //3 判断秒杀结束时间
//        if(voucher.getEndTime().isBefore(LocalDateTime.now())){
//            return Result.fail("秒杀已经结束！");
//        }
//
//        //4 判断库存是否充足
//        if(voucher.getStock() < 1){
//            return Result.fail("库存不足！");
//        }
//        Long userId = UserHolder.getUser().getId();
//
//        //        synchronized (userId.toString().intern()){  //不能用userId做锁对象是因为long类型如果超过128，每次new一个新对象，不是指向常量池
////           //创件代理对象
////            IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();
////            return proxy.createVoucherOrder(voucherId);
////        }
//
//        //新思路 使用分布式锁
//        //1 获取锁对象
//        SimpleRedisLock lock = new SimpleRedisLock("order" + userId, stringRedisTemplate);
//        boolean isLock = lock.tryLock(1200L);
//        //2 失败
//        if(!isLock){
//            return Result.fail("无法重复下单");
//        }
//        //3 成功执行业务
//        try{
//            IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();
//            return proxy.createVoucherOrder(voucherId);
//        }finally {
//            lock.unLock();
//        }
//
//    }

    @Transactional
    public void createVoucherOrder(VoucherOrder voucherOrder) {
        //判断用户是否已经购买过了
        Long userId = voucherOrder.getUserId();

           int count = query().eq("user_id", userId)
                   .eq("voucher_id", voucherOrder.getVoucherId()).count();
           if(count > 0){
               //用户已经买过了
               log.error("用户已经下过单了！");
           }
           //5 扣减库存
           boolean success = seckillVoucherService.update().setSql("stock = stock - 1")
                   .eq("voucher_id", voucherOrder.getVoucherId()).gt("stock", 0).update();
           if(!success){
               log.error("扣减失败！");
           }

           save(voucherOrder);


    }
}
